package com.xuecheng.media.service.impl;

import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoResponse;
import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.commons.constants.CommonConstants;
import com.xuecheng.commons.constants.CourseConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.MediaDto;
import com.xuecheng.commons.model.dto.MediaQueryDto;
import com.xuecheng.commons.model.dto.PageRequest;
import com.xuecheng.commons.model.dto.VodUploadDto;
import com.xuecheng.commons.model.vo.*;
import com.xuecheng.commons.utils.AuthInfoHolder;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.media.config.VodTemplate;
import com.xuecheng.media.domain.Media;
import com.xuecheng.media.mappers.MediaMapper;
import com.xuecheng.media.service.MediaService;
import com.xuecheng.web.exceptions.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 媒资信息 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-09-22
 */
@Service
public class MediaServiceImpl extends ServiceImpl<MediaMapper, Media> implements MediaService {

    @Autowired
    private VodTemplate vodTemplate;

    //获取上传凭证
    public ResponseResult<VodUploadVo> createToken(VodUploadDto dto) throws ClientException {
        //请求阿里云
        CreateUploadVideoResponse response = vodTemplate.createUploadVideo(dto.getTitle(), dto.getFileName());
        //构造返回
        VodUploadVo vo = new VodUploadVo();
        vo.setRequestId(response.getRequestId());
        vo.setUploadAddress(response.getUploadAddress());
        vo.setUploadAuth(response.getUploadAuth());
        vo.setVideoId(response.getVideoId());
        vo.setUserId(AuthInfoHolder.getUserId().toString());
        return ResponseResult.okResult(vo);
    }

    //刷新上传凭证
    public ResponseResult<VodUploadVo> refreshToken(String videoId) throws Exception {
        //请求阿里云
        RefreshUploadVideoResponse response = vodTemplate.refreshUploadVideo(videoId);
        //构造返回
        VodUploadVo vo = new VodUploadVo();
        vo.setRequestId(response.getRequestId());
        vo.setUploadAddress(response.getUploadAddress());
        vo.setUploadAuth(response.getUploadAuth());
        vo.setVideoId(response.getVideoId());
        vo.setUserId(AuthInfoHolder.getUserId().toString());
        return ResponseResult.okResult(vo);
    }

    //保存媒资
    public ResponseResult saveMedia(MediaDto dto) throws Exception {
        //1、判断dto的传入参数（略）
        //2、创建Media的对象
        Media media = BeanHelper.copyProperties(dto, Media.class);
        //2.1 设置阿里云的播放url，时长
        GetPlayInfoResponse playInfo = vodTemplate.getPlayInfo(dto.getFileId());
        List<GetPlayInfoResponse.PlayInfo> list = playInfo.getPlayInfoList();
        GetPlayInfoResponse.PlayInfo info = list.get(0);
        //获取播放地址
        String playURL = info.getPlayURL();
        //播放时长
        String duration = info.getDuration();
        media.setUrl(playURL);
        media.setTimelength(duration);
        //2.2 设置其他参数
        media.setCompanyName(AuthInfoHolder.getAuthInfo().getCompanyName());
        media.setCreateDate(new Date());
        media.setAuditStatus(CourseConstants.AUDIT_UNPAST_STATUS);
        media.setStatus(CommonConstants.USING_FLAG.toString());
        //3、保存
        boolean save = this.save(media);
        if(!save) {
            throw new BusinessException(ErrorCode.ERROR);
        }
        //4、返回
        return ResponseResult.okResult();
    }

    //分页查询媒资列表
    public ResponseResult<MediaVo> findAll(PageRequest request, MediaQueryDto dto) {
        //分页页码参数：Page
        Page<Media> pageParam = new Page<>(request.getPageNo(),request.getPageSize());
        //查询条件
        LambdaQueryWrapper<Media> qw = new LambdaQueryWrapper<>();
        if(!StringUtils.isEmpty(dto.getType())) {
            qw.eq(Media::getType, dto.getType());//判断条件，字段，数据
        }
        if(!StringUtils.isEmpty(dto.getFilename())) {
            qw.like(Media::getFilename, dto.getFilename());
        }
        //审核状态: 略过
//        if(!StringUtils.isEmpty(dto.getAuditStatus())) {
//            qw.eq(Media::getAuditStatus,dto.getAuditStatus());
//        }


        //查询：iPage<Media>
        Page<Media> page = this.page(pageParam, qw); //总条数，数据列表
        //转化
        long total = page.getTotal();
        List<Media> records = page.getRecords();
        List<MediaVo> vos = BeanHelper.copyWithCollection(records, MediaVo.class);

        return new PageResponseResult(total,vos);
    }

    //根据id查询媒资的播放地址
    public ResponseResult<ResourceVo> findMediaUrl(Long mediaId) throws Exception {
        //1、根据媒资id查询媒资对象
        Media media = this.getById(mediaId);
        //2、获取阿里云的视频id
        String fileId = media.getFileId();
        //3、调用工具类，获取视频的播放信息
        GetPlayInfoResponse playInfo = vodTemplate.getPlayInfo(fileId);
        List<GetPlayInfoResponse.PlayInfo> infos = playInfo.getPlayInfoList();
        GetPlayInfoResponse.PlayInfo info = infos.get(0);
        String playURL = info.getPlayURL();
        //4、构造返回
        ResourceVo vo = new ResourceVo();
        vo.setPlayUrl(playURL);
        return ResponseResult.okResult(vo);
    }
}
